package api

import (
	"gitee.com/war2001/NiuMaEasyGo/model"
	"gitee.com/war2001/NiuMaEasyGo/nm_core/middleware"
	"gitee.com/war2001/NiuMaEasyGo/nm_core/router"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// Menu 菜单结构
type Menu struct {
	ID        uint   `json:"id"`
	ParentID  uint   `json:"parentId"`
	Name      string `json:"name"`
	Path      string `json:"path"`
	Component string `json:"component"`
	Meta      Meta   `json:"meta"`
	Children  []Menu `json:"children,omitempty"`
}

// Meta 菜单元数据
type Meta struct {
	Title     string `json:"title"`
	Icon      string `json:"icon,omitempty"`
	Order     int    `json:"order,omitempty"`
	KeepAlive bool   `json:"keepAlive,omitempty"`
	AffixTab  bool   `json:"affixTab,omitempty"`
}

// MenuController 菜单控制器
type MenuController struct {
	userService model.UserService
}

// NewMenuController 创建菜单控制器
func NewMenuController(userService model.UserService) *MenuController {
	return &MenuController{
		userService: userService,
	}
}

// RegisterRoutes 注册路由 (旧方式，保留用于兼容)
func (c *MenuController) RegisterRoutes(r *gin.RouterGroup) {
	// 需要认证的接口
	menuGroup := r.Group("/menu")
	menuGroup.Use(middleware.JWTAuth())
	{
		menuGroup.GET("/list", c.GetMenuList)
		menuGroup.GET("/tree", c.GetMenuTree)
		menuGroup.POST("/create", c.CreateMenu)
		menuGroup.PUT("/update/:id", c.UpdateMenu)
		menuGroup.DELETE("/delete/:id", c.DeleteMenu)
	}
}

// GetMenuListMetadata 获取菜单列表元数据
func (c *MenuController) GetMenuListMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "菜单管理",
		Path:         "/system/menu",
		Component:    "/system/menu/index",
		Icon:         "menu",
		Permission:   "system:menu:list",
		ParentPath:   "/system",
		MenuType:     "menu",
		MenuCategory: "system",
		Method:       "GET",
		APIPath:      "/menu/list",
		RequireAuth:  true,
		OrderNum:     3,
	}
}

// GetMenuTreeMetadata 获取菜单树元数据
func (c *MenuController) GetMenuTreeMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "菜单树",
		Path:         "",
		Component:    "",
		Icon:         "",
		Permission:   "system:menu:tree",
		ParentPath:   "/system/menu",
		MenuType:     "button",
		MenuCategory: "system",
		Method:       "GET",
		APIPath:      "/menu/tree",
		RequireAuth:  true,
		OrderNum:     1,
	}
}

// CreateMenuMetadata 创建菜单元数据
func (c *MenuController) CreateMenuMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "创建菜单",
		Path:         "",
		Component:    "",
		Icon:         "",
		Permission:   "system:menu:add",
		ParentPath:   "/system/menu",
		MenuType:     "button",
		MenuCategory: "system",
		Method:       "POST",
		APIPath:      "/menu/create",
		RequireAuth:  true,
		OrderNum:     2,
	}
}

// UpdateMenuMetadata 更新菜单元数据
func (c *MenuController) UpdateMenuMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "更新菜单",
		Path:         "",
		Component:    "",
		Icon:         "",
		Permission:   "system:menu:edit",
		ParentPath:   "/system/menu",
		MenuType:     "button",
		MenuCategory: "system",
		Method:       "PUT",
		APIPath:      "/menu/update/:id",
		RequireAuth:  true,
		OrderNum:     3,
	}
}

// DeleteMenuMetadata 删除菜单元数据
func (c *MenuController) DeleteMenuMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "删除菜单",
		Path:         "",
		Component:    "",
		Icon:         "",
		Permission:   "system:menu:delete",
		ParentPath:   "/system/menu",
		MenuType:     "button",
		MenuCategory: "system",
		Method:       "DELETE",
		APIPath:      "/menu/delete/:id",
		RequireAuth:  true,
		OrderNum:     4,
	}
}

// GetMenuList 获取菜单列表
func (c *MenuController) GetMenuList(ctx *gin.Context) {
	// 从上下文中获取用户ID和角色ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		middleware.ResponseUnauthorized(ctx, "未获取到用户信息")
		return
	}

	roleID, exists := ctx.Get("role_id")
	if !exists {
		middleware.ResponseUnauthorized(ctx, "未获取到角色信息")
		return
	}

	// 记录日志
	zap.L().Info("获取菜单列表",
		zap.Any("userID", userID),
		zap.Any("roleID", roleID))

	// 这里可以从数据库中获取菜单数据
	// 目前使用 auth_controller.go 中的 getMenusByRoleID 函数
	// 未来可以改为从数据库获取

	middleware.ResponseSuccess(ctx, gin.H{
		"message": "请使用 /api/v1/auth/menu/list 接口获取菜单",
	})
}

// GetMenuTree 获取菜单树
func (c *MenuController) GetMenuTree(ctx *gin.Context) {
	// 从上下文中获取用户ID和角色ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		middleware.ResponseUnauthorized(ctx, "未获取到用户信息")
		return
	}

	// 记录日志
	zap.L().Info("获取菜单树", zap.Any("userID", userID))

	// TODO: 从数据库中获取菜单树
	// 这里暂时返回空数组
	middleware.ResponseSuccess(ctx, []Menu{})
}

// CreateMenu 创建菜单
func (c *MenuController) CreateMenu(ctx *gin.Context) {
	var menu Menu
	if err := ctx.ShouldBindJSON(&menu); err != nil {
		middleware.ResponseBadRequest(ctx, "无效的请求参数: "+err.Error())
		return
	}

	// TODO: 将菜单保存到数据库
	// 这里暂时只返回成功
	middleware.ResponseSuccess(ctx, gin.H{
		"message": "创建菜单成功",
		"menu":    menu,
	})
}

// UpdateMenu 更新菜单
func (c *MenuController) UpdateMenu(ctx *gin.Context) {
	id := ctx.Param("id")
	var menu Menu
	if err := ctx.ShouldBindJSON(&menu); err != nil {
		middleware.ResponseBadRequest(ctx, "无效的请求参数: "+err.Error())
		return
	}

	// TODO: 更新数据库中的菜单
	// 这里暂时只返回成功
	middleware.ResponseSuccess(ctx, gin.H{
		"message": "更新菜单成功",
		"id":      id,
		"menu":    menu,
	})
}

// DeleteMenu 删除菜单
func (c *MenuController) DeleteMenu(ctx *gin.Context) {
	id := ctx.Param("id")

	// TODO: 从数据库中删除菜单
	// 这里暂时只返回成功
	middleware.ResponseSuccess(ctx, gin.H{
		"message": "删除菜单成功",
		"id":      id,
	})
}
